package com.poklaan.frein.http;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.viewbinding.ViewBinding;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

public abstract class BaseAdapter<B extends ViewBinding, T> extends BaseQuickAdapter<T, BaseAdapter<B, T>.ViewHolder> {

    public BaseAdapter(List<T> data) {
        super(0, data);
    }

    public class ViewHolder extends BaseViewHolder {
        public final B binding;

        public ViewHolder(B binding, View view) {
            super(view);
            this.binding = binding;
        }

    }

    @NonNull
    @Override
    protected ViewHolder onCreateDefViewHolder(@NonNull ViewGroup parent, int viewType) {
        try {

            Type superClass = getClass().getGenericSuperclass();
            ParameterizedType parameterizedType = (ParameterizedType) superClass;
            Type[] typeArguments = parameterizedType.getActualTypeArguments();
            Class<B> viewBindingClass = (Class<B>) typeArguments[0];


            Method inflateMethod = viewBindingClass.getMethod("inflate", LayoutInflater.class, ViewGroup.class, boolean.class);
            B binding = (B) inflateMethod.invoke(null, LayoutInflater.from(getContext()), parent, false);

            return new ViewHolder(binding, binding.getRoot());
        } catch (Exception e) {
            throw new RuntimeException("Failed to create ViewHolder", e);
        }
    }

    @Override
    protected void convert(@NonNull ViewHolder holder, T item) {
        convert(holder.binding, item);
    }

    protected abstract void convert(B binding, T item);
}